package a.codetop;

import org.junit.Test;

public class _19大数加法_字符串相加 {
    @Test
    public void test() {
        System.out.println(addStrings("456","77"));
    }

    //板子
    public String addStrings(String num1, String num2) {

        int h1 = num1.length() - 1, h2 = num2.length() - 1;
        int cr = 0;
        StringBuilder sb = new StringBuilder();

        while (h1 >= 0 || h2 >= 0 || cr != 0) {
            //指针为负数索引，补0
            int x = h1 >= 0 ? num1.charAt(h1) - '0' : 0;
            int y = h2 >= 0 ? num2.charAt(h2) - '0' : 0;

            int sum = x + y + cr;
            int shang = sum/10; cr=shang;
            int yushu = sum%10; sb.append(yushu);

            h1--;h2--;
        }

        return sb.reverse().toString();

    }



    //代码太长
    public String addStrings_tolong(String num1, String num2) {
        int h1=num1.length()-1,h2=num2.length()-1;
        int cr=0;
        StringBuilder sb = new StringBuilder();

        while(h1>=0 && h2>=0){
            int sum = cr + Integer.parseInt(num1.charAt(h1)+"") + Integer.parseInt(num2.charAt(h2)+"");
            int shang = sum/10; cr=shang;
            int yushu = sum%10; sb.append(yushu);

            h1--;h2--;
        }
        //同长度
        if(h1==-1 && h2==-1){

        }
        //h1还剩
        else if(h1>=0 && h2==-1){
            for (int k=h1;k>=0;k--){
                int sum = cr + Integer.parseInt(num1.charAt(k)+"") ;
                int shang = sum/10; cr=shang;
                int yushu = sum%10; sb.append(yushu);
            }
        }
        //h2还剩
        else if(h1==-1 && h2>=0){
            for (int k=h2;k>=0;k--){
                int sum = cr + Integer.parseInt(num1.charAt(k)+"") ;
                int shang = sum/10; cr=shang;
                int yushu = sum%10; sb.append(yushu);
            }
        }
        //加完还需进一位1
        if(cr==1){
            sb.append(1);
        }

        return sb.reverse().toString();
    }

}
